/**
 * check the permission of xing zheng teacher
 */

const jwt = require('jsonwebtoken')
const redis = require('redis')
const configs = require('../config')
const $ = require('../utils/common')
const redis_config = configs.redis_config
const key = configs.json_web_token_key

const check_xingzheng_permission = async function(req, res, next) {

    try {

       const path = req._parsedUrl.pathname

       req.body.token = req.body.token || req.query.token
   
       if (!req.body.token) {
           $.sendMessage(res, 1015, 'token没有传')
           return
       }
   
    //    $.log('行政-当前路径:', path)
    //    $.log('行政-当前token:', req.body.token)
   
       
       //解析token
       var token = await jwt.verify(req.body.token, key, (err, data) => {
           if (err) {
               $.sendMessage(res, 1006, 'token解析失败')
               return
           }
           return data
       })
    //    $.log('解析后的token：', token)

       if (token.user_role != 'xingzheng_teacher') {
           $.sendMessage(res, 1014, '您没有权限访问')
           return
       }


       // 从redis获取token
       var redis_client = await redis.createClient({port:redis_config.PORT, host: redis_config.HOST,no_ready_check: true})
       await redis_client.auth(configs.redis_config.PASSWORD)
       redis_client.get(token.user_name, (err, data) => {
        //    $.log('data from redis: ', data)

           if (err) {
               $.sendMessage(res, 1012, 'redis服务器出错，请联系管理员')
               return
           }

           if (data == null) {
               $.sendMessage(res, 1011, 'token过期请重新登陆')
               return
           }

           // $.log('type of req.body.token:', typeof token)
           // $.log('type of token from redis:', typeof data)
           // $.log('req.body.token:', req.body.token)
           // $.log('token from redis:', data)

           if (data.trim() != req.body.token.trim() ) {
               $.sendMessage(res, 1013, '从redis获取的 token和 传来的token不一致2')
               return
           }

           // 身份验证通过，去执行后面代码
           req['user_name'] = token.user_name
           next()
           return
       })

    }

    catch(error) {
        $.sendMessage(res, 0000, error)
        return
    }
   
}

module.exports = check_xingzheng_permission